<script type="text/javascript" src="resources/node-red-contrib-knx-ultimate/htmlUtils.js"></script>

<script type="text/javascript">
    RED.nodes.registerType('knxUltimateWatchDog', {
        category: "KNX Ultimate",
        color: '#C7E9C0',
        defaults: {
            server: { type: "knxUltimate-config", required: true },
            topic: { value: "12/0/0" },
            maxRetry: { value: 6 }, // After this number is reached, throw a connection error
            retryInterval: { value: 10 },
            name: { value: "" },
            autoStart: { value: true },
            checkLevel: { value: "Ethernet" }
        },
        inputs: 1,
        outputs: 1,
        outputLabels: ["Output"],
        icon: "node-watchdog-icon.svg",
        label: function () {
            return ((this.name || "KNX Watchdog") + " " + (this.checkLevel == "Ethernet" ? "Gateway IP" : this.topic));
        },
        paletteLabel: "KNX WatchDog",
        oneditprepare: function () {
            // Go to the help panel
            try {
                RED.sidebar.show("help");
            } catch (error) { }

            $("#advancedOptionsAccordion").accordion({
                header: "h3",
                heightStyle: "content",
                collapsible: true,
                active: false
            });

            $("#node-input-checkLevel").on('change', function () {
                if ($("#node-input-checkLevel").val() == "Ethernet") {
                    $("#divHost").hide();
                } else {
                    $("#divHost").show();
                }
            })

            if (checkLevel !== "Ethernet") {
                $("#divHost").hide();
            } else {
                $("#divHost").show();
            }
        },
        oneditsave: function () {
            // Return to the info tab
            try {
                RED.sidebar.show("info");
            } catch (error) { }


        }

    })

</script>

<script type="text/html" data-template-name="knxUltimateWatchDog">
    <div class="form-row">
        <b><span data-i18n="knxUltimateWatchDog.title"></span></b>&nbsp&nbsp<span style="color:red" data-i18n="[html]knxUltimateWatchDog.helplink"></span>
        <br/><br/>

        <label for="node-input-server"><i class="fa fa-tag"></i> <span data-i18n="knxUltimateWatchDog.properties.node-input-server"></span> </label>
        <input type="text" id="node-input-server">
    </div>
    <div class="form-row">
        <label for="node-input-checkLevel"><i class="fa fa-search"></i> <span data-i18n="knxUltimateWatchDog.properties.node-input-checkLevel"></span> </label>
        <select id="node-input-checkLevel">
            <option value="Ethernet" data-i18n="knxUltimateWatchDog.selectlists.Ethernet"></option>
            <option value="Eth+KNX" data-i18n="knxUltimateWatchDog.selectlists.EthKNX"></option>
        </select>
    </div>
    <div class="form-row" id="divHost">
        <label for="node-input-topic"><i class="fa fa-tasks"></i> <span data-i18n="knxUltimateWatchDog.properties.node-input-topic"></span></label>
        <input type="text" id="node-input-topic" data-i18n="[placeholder]knxUltimateWatchDog.placeholder.monitor">
    </div>
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="knxUltimateWatchDog.properties.node-input-name"></span> </label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]knxUltimateWatchDog.properties.node-input-name">
    </div>
    <div class="form-row">
        <input type="checkbox" id="node-input-autoStart" style="display:inline-block; width:auto; vertical-align:top;">
        <label style="width:auto" for="node-input-autoStart">&nbsp;&nbsp;<i class="fa fa-play-circle"></i> <span data-i18n="knxUltimateWatchDog.properties.node-input-autoStart"></span> </label>
    </div>    
    
    <div id="advancedOptionsAccordion">
        <h3><span data-i18n="knxUltimateWatchDog.properties.advancedOptionsAccordion"></span></h3>
        <div>
            <p>
                <div class="form-row">
                    <label for="node-input-retryInterval"><i class="fa fa-clock-o"></i> <span data-i18n="knxUltimateWatchDog.properties.node-input-retryInterval"></span></label>
                    <input type="text" id="node-input-retryInterval">
                </div>
                <div class="form-row">
                    <label for="node-input-maxRetry"><i class="fa fa-undo"></i> <span data-i18n="knxUltimateWatchDog.properties.node-input-maxRetry"></span></label>
                    <input type="text" id="node-input-maxRetry">
                </div>
            </p>
        </div>
    </div>        
</script>

<script type="text/markdown" data-help-name="knxUltimateWatchDog">
<p>Checks the connection to the Gateway or to a specific KNX device</p>

# WatchDog

**What does it do?**

1. Checks for the healty of KNX BUS communication/connection by sending a telegram at regular intervals, watching for a response and sends a msg to the flow if a connection to KNX Bus is broken. Two check levels, see below.
2. Programmatically changes the Configuration Node parameters, thus the connection to your KNX/IP Router/Interface (for example, if you have 2 KNX/IP Routers and you want to switch between the two for connection backup).
3. Forces the gateway's connection/disconnection from/to the KNX BUS.

## Ethernet level and KNX Twisted Pair level checks

The WatchDog has two check levels.  

The first, checks only the connection between knx-Ultimate and the KNX/IP Interface.  

The second one, checks the entire route, from knx-Ultimate Gateway node to ethernet, then to KNX TP media and vice versa; this implies the use of a physical device, responding to a read requests.

The WatchDog node is a powerfull node for signalling errors and connection problems. <br />

You can send an Email to the KNX installer responsible to your Building, or you can automatically switch to a backup KNX/IP Router/Interface in your installation.

## SETTINGS

| Property                      | Description                                                                                         |
| ----------------------------- | --------------------------------------------------------------------------------------------------- |
| Gateway                       | Selected KNX gateway.                                                                               |
| Group Address to monitor      | The node will send a telegram to this address and monitors the message flowing through the KNX BUS. |
| Name                          | Node Name                                                                                           |
| Auto start the watchdog timer | The watchdog timer starts automatically on deploy or on node-red start.                             |
| Check level                   | See below                                                                                           |

**Check level**

> ***Ethernet*** : *Chechks the connection between knx-ultimate Gateway in unicast mode and your KNX IP Interface.<br />

<img src="https://raw.githubusercontent.com/Supergiovane/node-red-contrib-knx-ultimate/master/img/wiki/WatchDogEthernetLevel.png"
    width="90%"><br />

> ***Ethernet and KNX TP*** : Complete check. It works either with KNX/IP Routers and KNX/IP Interfaces (as well as

address set), it checks the connection between KNX-Ultimate and this physical KNX device, by issuing a read request and by awaiting a response telegram from this device. Any error on the ethernet trunk or on the KNX Twisted Pair trunk will be notified. To setup this check level, you need to reserve a Group Address and add it to a "Status" output of your KNX Actuator. For example, if you have a light actuator, it has for sure a "light status" output that can **respond** to a **read request**.

About this picture, in ETS, assign an Output of this Gira KNX Actuator to a Light **Status** (for example 12/0/0). Everytime the Watchdog node asks for the status, the Gira KNX Actuator will respond. The WatchDog then know, that your KNX

Twisted Pair connection is up and running.

<img src="https://raw.githubusercontent.com/Supergiovane/node-red-contrib-knx-ultimate/master/img/wiki/WatchDogEthernetKNXTPLevel.png"
    width="90%"><br />



## ADVANCED OPTIONS

| Property | Description |
| -------- | ----------- |
|   Retry interval (in seconds)       |    The node sends a telegram to the KNX bus at this time interva, in seconds.         |
| Number of retry before giving an error |After the telegram has been sent for this amount of times, without any response from KNX Bus, the node throws an error. |

# MESSAGE OUTPUT FROM THE WATCHDOG

The WatchDog node outs a message whenever it receives an error from one of your knx-ultimate node in your flows, or whenever the internal Watchdog intercepts a KNX Bus communication error.<br />

**In case of Watchdog self connection problem**

<a href="https://github.com/Supergiovane/node-red-contrib-knx-ultimate/wiki/WatchDog-Configuration"
    target="_blank">Please see here.</a>

```javascript

msg = {
type:"BUSError"
checkPerformed: "Ethernet" for basic check, or "Eth+KNX" for full check.
nodeid: "23HJ.2355" // (The node ID causing the error, so you can find it using node-red "search" funtion)
payload: true
description: // (whatever error description)
}

```

<br />

**In case of one of your KNX-Ultimate nodes is in trouble**

```javascript

msg = {
type:"NodeError"
checkPerformed: "Self KNX-Ultimate node reporting a red color status"
nodeid: "23HJ.2355" // (The node ID causing the error, so you can find it using node-red "search" funtion)
payload: true
description: // (KNX-Ultimate node reports his error here)
completeError:{
nodeid: "23HJ.2355" // (The node ID causing the error, so you can find it using node-red "search" funtion)
topic: "0/1/1" // (or the custom topic you set in the knx-ultimate node)
devicename: "Kitchen Light"
GA: "0/1/1"

}
}

```

<br />

**In case of a new gateway configuration is called via setGatewayConfig**

```javascript

msg = {
type:"setGatewayConfig"
checkPerformed: "The Watchdog node changed the gateway configuration."
nodeid: "23HJ.2355" // (The node ID issuing the setGatewayConfig, so you can find it using node-red "search" funtion)
payload: true
description: "New Config issued to the gateway. IP:224.0.23.12 Port:3671 PhysicalAddress:15.15.1
BindLocalInterface:Auto"
completeError:""
}

```

<br />

**Forced connection/disconnection**

```javascript

msg = {
type:"connectGateway"
checkPerformed: "The Watchdog issued a connection/disconnection to the gateway."
nodeid: "23HJ.2355" // (The node ID issuing the connection/disconnection request, so you can find it using node-red
"search" funtion)
payload: true // true if you requested the connection, false if you requested the disconnection
description: "Connection"
completeError:""
}

```

<br />

---

# INPUT FLOW MESSAGE

The WatchDog node accepts flow's input and transmits flow's output. Below, an explanation of the message's format to be sent to or trasmitted from the node.

## START AND STOP THE WATCHDOG

To start and stop the watchdog, you can pass this as message to the node<br />

**START WATCHDOG** <br />

```javascript

// Start the WatchDog
msg.start = true;
return msg;

```

**STOP WATCHDOG** <br />

```javascript

// Start the WatchDog
msg.start = false;
return msg;

```

## CHANGE THE KNX/IP ROUTER/INTERFACE SETTINGS ON THE FLY

With **msg.setGatewayConfig**, you can change the IP, Port, Physical Address, Protocol and so on of your KNX/IP Interface or Router, previously set in the Config-Node<br />

The Config-Node will change the settings and reconnect with new parameters.<br />

Be careful, if you restart node-red, the new settings are reverted to the settings specified in the Config-Node.<br />

ALL parameters are OPTIONAL <br />

Please <a href="https://github.com/Supergiovane/node-red-contrib-knx-ultimate/wiki/-Sample---WatchDog"

    target="_blank">see here for other examples.</a>.

```javascript

// IP: IP of your KNX/IP Router or Interface
// Port: Port of your KNX/IP Router or Interface
// PhysicalAddress: Physical address your KNX/IP Router or Interface (this is not a Group Address, this is a physical address indicating the physical device in your KNX installation)
// BindToEthernetInterface: "Auto" (for automatic detection) or the ethernet interface name, for example "en0".
// Protocol: "TunnelUDP" or "TunnelTCP" or "Multicast"
// importCSV: the ETS exported CSV or ESF. Please see the text format in the Gateway Config Wiki Page and in the youtube
video.
// All these parameters are optional

msg.setGatewayConfig={IP:"224.0.23.12",Port:3671,PhysicalAddress:"15.15.1",BindToEthernetInterface:"Auto",
Protocol:"Multicast", importCSV:`"Group name" "Address" "Central" "Unfiltered" "Description" "DatapointType" "Security"
"Attuatori luci" "0/-/-" "" "" "" "" "Auto"
"Luci primo piano" "0/0/-" "" "" "" "" "Auto"
"Luce camera da letto" "0/0/1" "" "" "" "DPST-1-1" "Auto"};`
return msg;

```

All properties are optional. For example, to only change the IP:

```javascript

// IP: IP of your KNX/IP Router or Interface
msg.setGatewayConfig={IP:"224.0.23.12"};
return msg;

```

**FORCE GATEWAY'S DISCONNECTION AND DISABLE AUTO RECONNECTION ATTEMPTS** <br />

```javascript

// Force the gateway's disconnection from the BUS and stop the reconnection's attempts.
msg.connectGateway = false;
return msg;

```

**FORCE GATEWAY'S CONNECTION AND ENABLE THE AUTO RECONNECTION ATTEMPTS** <br />

```javascript

// Force the gateway's connection to the BUS and activate the reconnection's attempts.
msg.connectGateway = true;
return msg;

```

## SEE ALSO

[Sample WatchDog](https://github.com/Supergiovane/node-red-contrib-knx-ultimate/wiki/-Sample---WatchDog)
</script>